//
//  THWelcomeController.swift
//  TongHuoDemo
//
//  Created by rimi on 2017/5/2.
//  Copyright © 2017年 rimi. All rights reserved.
//

import UIKit
let btnW: CGFloat = 60

class THWelcomeController: UIViewController {
    
    var timer: Timer? // 自动跳过的定时器
    var time: Int = 5 // 自动跳过时长
    // 懒加载
    lazy var timeBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.frame = CGRect(x: UIScreen.main.bounds.width-btnW-8, y: 8, width: btnW, height: 20)
        btn.backgroundColor = UIColor.gray
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        btn.layer.cornerRadius = 5
        btn.layer.masksToBounds = true
        btn.setTitle("跳过 5", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 添加欢迎视图
        let welcomeVc = UIStoryboard(name: "LaunchScreen", bundle: nil).instantiateInitialViewController()
        addChildViewController(welcomeVc!)
        view.addSubview((welcomeVc?.view)!)
        
        // 添加按钮
        timeBtn.addTarget(self, action: #selector(timeBtnClicked), for: .touchUpInside)
        view.addSubview(timeBtn)
        
        // 开始计时
        startTimer()
    }

    // 开始定时器的方法
    func startTimer() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(welcomePageShow), userInfo: nil, repeats: true)
    }
    
    // 定时器回调方法
    func welcomePageShow() {
        time -= 1
        if time < 1 {
            // 跳转
            timeBtnClicked()
            return
        }
        // 修改按钮标题
        timeBtn.setTitle("跳过 \(time)", for: .normal)
    }
    
    // 按钮的点击回调方法
    func timeBtnClicked() {
        // 停止定时器
        timer?.invalidate()
        timer = nil
        // 跳转到标签控制器
        UIApplication.shared.keyWindow?.rootViewController = THTabBarController()
    }
    
    // 隐藏状态栏
    override var prefersStatusBarHidden: Bool {
        return true
    }

}
